package com.wskh.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wskh.edu.entity.Chapter;
import com.wskh.edu.entity.Course;
import com.wskh.edu.entity.CourseDescription;
import com.wskh.edu.entity.Video;
import com.wskh.edu.entity.chapter.ChapterVo;
import com.wskh.edu.entity.chapter.VideoVo;
import com.wskh.edu.entity.course.CourseListVo;
import com.wskh.edu.entity.course.CourseSearchObj;
import com.wskh.edu.entity.frontvo.CourseFrontVo;
import com.wskh.edu.entity.vo.CourseInfoVo;
import com.wskh.edu.entity.vo.CoursePublishVo;
import com.wskh.edu.entity.vo.front.CourseWebVo;
import com.wskh.edu.mapper.CourseMapper;
import com.wskh.edu.service.ChapterService;
import com.wskh.edu.service.CourseDescriptionService;
import com.wskh.edu.service.CourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wskh.edu.service.VideoService;
import com.wskh.serviceBase.exception.XbException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.util.StringUtils;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author wskh
 * @since 2021-10-14
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private CourseDescriptionService courseDescriptionService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private VideoService videoService;


    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        //保存课程基本信息
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoVo, course);
        boolean resultCourseInfo = this.save(course);
        if (!resultCourseInfo) {
            throw new XbException(500, "课程信息保存失败");
        }
        //保存课程详情信息
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription());
        courseDescription.setId(course.getId());
        boolean resultDescription = courseDescriptionService.save(courseDescription);
        if (!resultDescription) {
            throw new XbException(500, "课程详情信息保存失败");
        }
        return course.getId();
    }

    @Override
    public CourseInfoVo getCourseInfoVoByCourseId(String courseId) {
        // 返回对象
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        // 查询课程表
        Course course = baseMapper.selectById(courseId);
        //查询课程描述表
        CourseDescription courseDescription = courseDescriptionService.getById(courseId);
        // 获取课程视图对象
        if (course != null) {
            BeanUtils.copyProperties(course, courseInfoVo);
        }
        if (courseDescription != null) {
            BeanUtils.copyProperties(courseDescription, courseInfoVo);
        }
        return courseInfoVo;
    }

    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {


        // 修改课程信息
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoVo, course);
        int update = baseMapper.update(course, null);
        if (update < 0) {
            throw new XbException(500, "修改课程信息失败");
        }

        // 修改课程描述信息
        CourseDescription courseDescription = courseDescriptionService.getById(courseInfoVo.getId());
        BeanUtils.copyProperties(courseInfoVo, courseDescription);
        boolean update1 = courseDescriptionService.update(courseDescription, null);
        if (!update1) {
            throw new XbException(500, "修改课程描述信息失败");
        }

    }

    @Override
    public boolean publishCourse(CoursePublishVo coursePublish) {

        //将课程添加到课程表中
        Course course = new Course();
        BeanUtils.copyProperties(coursePublish, course);
        course.setSubjectId(coursePublish.getSubjectLevelTwoId());
        course.setSubjectParentId(coursePublish.getSubjectLevelOneId());
        int insert = baseMapper.insert(course);
        if (insert < 0) {
            return false;
        }


        // 设置id
        coursePublish.setId(course.getId());

        // 将描述信息添加到数据库中
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setId(course.getId());
        courseDescription.setDescription(coursePublish.getDescription());
        boolean save = courseDescriptionService.save(courseDescription);
        if (!save) {
            return false;
        }

        // 将章节添加到章节表中
        List<ChapterVo> chapterVoList = coursePublish.getChapterVoList();
        for (ChapterVo chapterVo : chapterVoList) {
            Chapter chapter = new Chapter();
            BeanUtils.copyProperties(chapterVo, chapter);
            chapter.setCourseId(course.getId());
            boolean save1 = chapterService.save(chapter);
            if (!save1) {
                return false;
            }
            // 将章节中的小节添加到小节表中
            List<VideoVo> children = chapterVo.getChildren();
            for (VideoVo child : children) {
                Video video = new Video();
                BeanUtils.copyProperties(child, video);
                video.setCourseId(course.getId());
                video.setChapterId(chapter.getId());
                boolean save2 = videoService.save(video);
                if (!save2) {
                    return false;
                }
            }
        }
        System.out.println(coursePublish);
        return true;
    }

    // 更新课程信息
    @Override
    public boolean updateCourse(CoursePublishVo coursePublish) {

        //更新课程信息
        Course course = new Course();
        BeanUtils.copyProperties(coursePublish, course);
        course.setSubjectId(coursePublish.getSubjectLevelTwoId());
        course.setSubjectParentId(coursePublish.getSubjectLevelOneId());
        int update = baseMapper.updateById(course);
        if (update < 0) {
            return false;
        }

        // 更新描述信息
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setId(course.getId());
        System.out.println("id = " + course.getId());
        courseDescription.setDescription(coursePublish.getDescription());
        boolean update1 = courseDescriptionService.updateById(courseDescription);
        if (!update1) {
            return false;
        }

        // 先将库中该课程原有的章节和小节全部删除
        boolean b = chapterService.removeChapterByCourseId(course.getId());
        if (!b) {
            return false;
        }

        // 更新章节
        List<ChapterVo> chapterVoList = coursePublish.getChapterVoList();
        for (ChapterVo chapterVo : chapterVoList) {
            Chapter chapter = new Chapter();
            BeanUtils.copyProperties(chapterVo, chapter);
            chapter.setCourseId(course.getId());
            boolean save1 = chapterService.save(chapter);
            if (!save1) {
                return false;
            }
            // 更新小节
            List<VideoVo> children = chapterVo.getChildren();
            for (VideoVo child : children) {
                Video video = new Video();
                BeanUtils.copyProperties(child, video);
                video.setCourseId(course.getId());
                video.setChapterId(chapter.getId());
                boolean save2 = videoService.save(video);
                if (!save2) {
                    return false;
                }
            }
        }

        return true;
    }

    @Override
    public List<Course> selectByTeacherId(String id) {

        QueryWrapper<Course> queryWrapper = new QueryWrapper<Course>();
        queryWrapper.eq("teacher_id", id);
        //按照最后更新时间倒序排列
        queryWrapper.orderByDesc("gmt_modified");
        List<Course> courses = baseMapper.selectList(queryWrapper);

        return courses;

    }

    @Override
    public Map<String, Object> getFrontCourseList(Page<Course> pageParam, CourseFrontVo courseFrontVo) {

        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();

        System.out.println("courseFrontVo = "+courseFrontVo);

        if(courseFrontVo!=null){
            if (!StringUtils.isEmpty(courseFrontVo.getSubjectParentId())) {
                queryWrapper.eq("subject_parent_id",
                        courseFrontVo.getSubjectParentId());
            }
            if (!StringUtils.isEmpty(courseFrontVo.getSubjectId())) {
                queryWrapper.eq("subject_id", courseFrontVo.getSubjectId());
            }
            if (!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())) {
                queryWrapper.orderByDesc("buy_count");
            }
            if (!StringUtils.isEmpty(courseFrontVo.getGmtCreateSort())) {
                queryWrapper.orderByDesc("gmt_create");
            }
            if (!StringUtils.isEmpty(courseFrontVo.getPriceSort())) {
                queryWrapper.orderByDesc("price");
            }
        }

        baseMapper.selectPage(pageParam, queryWrapper);

        List<Course> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();
        boolean hasPrevious = pageParam.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;

    }

    @Override
    public CourseWebVo selectInfoWebById(String id) {
        this.updatePageViewCount(id);
        return baseMapper.selectInfoWebById(id);
    }

    public void updatePageViewCount(String id) {
        Course course = baseMapper.selectById(id);
        course.setViewCount(course.getViewCount() + 1);
        baseMapper.updateById(course);
    }

    @Override
    // 删除课程（包括其中的章节信息，描述信息）
    public boolean deleteCourseById(String id) {

        // 根据课程id删除课程
        int i = baseMapper.deleteById(id);
        if (i < 0) {
            return false;
        }

        // 根据课程id删除描述信息
        QueryWrapper<CourseDescription> courseDescriptionQueryWrapper = new QueryWrapper<>();
        courseDescriptionQueryWrapper.eq("id", id);
        boolean b = courseDescriptionService.remove(courseDescriptionQueryWrapper);
        if (!b) {
            return false;
        }

        // 根据课程id删除章节信息
        QueryWrapper<Chapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id", id);
        boolean remove = chapterService.remove(chapterQueryWrapper);
        if (!remove) {
            return false;
        }

        // 根据课程id删除章节中的小节
        QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("course_id", id);
        boolean remove1 = videoService.remove(videoQueryWrapper);
        if (!remove1) {
            return false;
        }

        return true;
    }

}
